<?php


class SalesDataModel extends BaseModel {
    public static $db;
    public function getDbConnection(){
        if(self::$db!==null){
            return self::$db;
        }else{
            self::$db=Yii::app()->getComponent('db_count');
            if(self::$db instanceof CDbConnection)
                return self::$db;
            else
                throw new CDbException('连接出错');                    
        }            
    }
    public function tableName() {
        return '{{sales_data}}';
    }

    public function rules() {
        return array(
            array('TOrderNumber', 'unique', 'message' => '该订单编号已经存在！'),
            array('SalesID, TCreateTime, TGoodsName, TGoodsNumber, TPrice, TCommission, TProductID, TNice, TSop, TOrderNumber, Source, GoodsID, GoodsBmID, AdminID, StartTime, EndTime, ItemType, PromoPrice, CheckTime, StartSales, Sales, IsAnalysis, AddTime', 'safe'),
        );
    }

    //关联查询
    public function relations() {
        return array(
            'GoodsModel' => array(self::BELONGS_TO, 'GoodsModel', 'GoodsID'),
        );
    }

    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array(
            'SalesID' => '主键ID',
            'TCreateTime' => '订单时间',
            'TGoodsName' => '商品名',
            'TGoodsNumber' => '商品ID',
            'TPrice' => '价格',
            'TCommission' => '折率',
            'TProductID' => '产品ID',
            'TNice' => '旺旺号',
            'TSop' => '订单',
            'TOrderNumber' => '订单号',
            'Source' => '来源',
            'GoodsID' => '商品主键ID',
            'GoodsBmID' => '报名ID',
            'AdminID' => '后台操作人员ID',
            'StartTime' => '上架时间',
            'EndTime' => '下架时间',
            'ItemType' => '店铺类型',
            'PromoPrice' => '折扣价',
            'CheckTime' => '操作时间',
            'StartSales' => '初始销量',
            'Sales' => '销量',
            'IsAnalysis' => '是否分析',
            'AddTime' => '记录添加时间',
        );
    }
    public function search()
    {
        // @todo Please modify the following code to remove attributes that should not be searched.

        $criteria=new CDbCriteria;

        $criteria->compare('SalesID',$this->SalesID,true);
        $criteria->compare('TCreateTime',$this->TCreateTime,true);
        $criteria->compare('TGoodsName',$this->TGoodsName,true);
        $criteria->compare('TGoodsNumber',$this->TGoodsNumber,true);
        $criteria->compare('TPrice',$this->TPrice,true);
        $criteria->compare('TCommission',$this->TCommission,true);
        $criteria->compare('TProductID',$this->TProductID,true);
        $criteria->compare('TNice',$this->TNice,true);
        $criteria->compare('TSop',$this->TSop,true);
        $criteria->compare('TOrderNumber',$this->TOrderNumber,true);
        $criteria->compare('Source',$this->Source);
        $criteria->compare('GoodsID',$this->GoodsID,true);
        $criteria->compare('GoodsBmID',$this->GoodsBmID,true);
        $criteria->compare('AdminID',$this->AdminID,true);
        $criteria->compare('StartTime',$this->StartTime,true);
        $criteria->compare('EndTime',$this->EndTime,true);
        $criteria->compare('ItemType',$this->ItemType);
        $criteria->compare('PromoPrice',$this->PromoPrice,true);
        $criteria->compare('CheckTime',$this->CheckTime,true);
        $criteria->compare('StartSales',$this->StartSales,true);
        $criteria->compare('Sales',$this->Sales,true);
        $criteria->compare('IsAnalysis',$this->IsAnalysis);
        $criteria->compare('AddTime',$this->AddTime,true);

        return new CActiveDataProvider($this, array(
            'criteria'=>$criteria,
        ));
    }

    public function createSearchCriteria()
    {
        // @todo Please modify the following code to remove attributes that should not be searched.

        $criteria=new CDbCriteria;

        $criteria->compare('SalesID',$this->SalesID,true);
        $criteria->compare('TCreateTime',$this->TCreateTime,true);
        $criteria->compare('TGoodsName',$this->TGoodsName,true);
        $criteria->compare('TGoodsNumber',$this->TGoodsNumber,true);
        $criteria->compare('TPrice',$this->TPrice,true);
        $criteria->compare('TCommission',$this->TCommission,true);
        $criteria->compare('TProductID',$this->TProductID,true);
        $criteria->compare('TNice',$this->TNice,true);
        $criteria->compare('TSop',$this->TSop,true);
        $criteria->compare('TOrderNumber',$this->TOrderNumber,true);
        $criteria->compare('Source',$this->Source);
        $criteria->compare('GoodsID',$this->GoodsID,true);
        $criteria->compare('GoodsBmID',$this->GoodsBmID,true);
        $criteria->compare('AdminID',$this->AdminID,true);
        $criteria->compare('StartTime',$this->StartTime,true);
        $criteria->compare('EndTime',$this->EndTime,true);
        $criteria->compare('ItemType',$this->ItemType);
        $criteria->compare('PromoPrice',$this->PromoPrice,true);
        $criteria->compare('CheckTime',$this->CheckTime,true);
        $criteria->compare('StartSales',$this->StartSales,true);
        $criteria->compare('Sales',$this->Sales,true);
        $criteria->compare('IsAnalysis',$this->IsAnalysis);
        $criteria->compare('AddTime',$this->AddTime,true);

        return  $criteria;  
    }    

    /**
     * 根据excel导入数据
     * 数据全部都是存放在SalesDataModel_excelImport  这个地方了  ，，根据文件然后导入数据
     * @param type $path excel文件路径
     * @return boolean
     */
    public function excelImport($path) {
        if (!file_exists($path)) {
            return false;
        }
        set_time_limit(0);
        ini_set('memory_limit', '256M');
        //require_once Yii::app()->basePath . '/extensions/Excel/reader.php';
        require_once Yii::app()->basePath . '/extensions/Excel/cvstoarray.php';
        $csv = new CvsToArray($path);
        $dataList = $csv->get_array();
        if (empty($dataList)) {
            return false;
        }
        $memcache = new Memcache();
        $memcache->connect('127.0.0.1', 11211);
        //$memcache->useMemcached = false;
        $memcache->set('SalesDataModel_excelImport', $dataList, 0, 600);
        return true;
    }

    /**
     * 数据导入
     * $rs  是导入的数据的其中一行，是以数据形式存在的。。。。。
     * @param type $rs
     * @param type $Source       导入的类型，是U站还是官网导入。。。。。
     * @return boolean
     */
    public function import($rs, $Source = 0) {
        if (empty($rs)) {
            return false;
        }
        if (empty($rs[10]) || empty($rs[12])) {
            return false;
        }
        $arrData = array(
            'TCreateTime' => strtotime($rs[0]),
            'TGoodsName' => $rs[1],
            'TGoodsNumber' => $rs[2],
            'TPrice' => $rs[3],
            'TCommission' => number_format($rs[7], 5) / 100,
            'TProductID' => $rs[10],
            'TNice' => $rs[11],
            'TSop' => $rs[12],
            'TOrderNumber' => $rs[20],
            'Source' => $Source,
        );
        //本站存储的商品信息
        $arrGoodsData = $this->getGoodsIndo($arrData['TProductID'], $arrData['TCreateTime']);
        if (!empty($arrGoodsData)) {
            $arrData['GoodsID'] = $arrGoodsData['GoodsID'];
            $arrData['GoodsBmID'] = $arrGoodsData['GoodsBmID'];
            $arrData['AdminID'] = $arrGoodsData['AdminID'];
            $arrData['StartTime'] = $arrGoodsData['StartTime'];
            $arrData['EndTime'] = $arrGoodsData['EndTime'];
            $arrData['ItemType'] = $arrGoodsData['ItemType'];
            $arrData['PromoPrice'] = $arrGoodsData['PromoPrice'];
            $arrData['CheckTime'] = $arrGoodsData['UpdateTime'];
            $arrData['StartSales'] = $arrGoodsData['StartSales'];
            $arrData['Sales'] = $arrGoodsData['Sales'];
            $arrData['IsAnalysis'] = 0;
        } else {
            $arrData['GoodsID'] = 0;
            $arrData['GoodsBmID'] = 0;
            $arrData['AdminID'] = 0;
            $arrData['StartTime'] = 0;
            $arrData['EndTime'] = 0;
            $arrData['ItemType'] = 0;
            $arrData['PromoPrice'] = 0;
            $arrData['CheckTime'] = 0;
            $arrData['StartSales'] = 0;
            $arrData['Sales'] = 0;
            $arrData['IsAnalysis'] = 0;
        }

        $objModel = self::model()->find(BaseModel::getC(array('TOrderNumber' => $arrData['TOrderNumber'])));
        if(!$objModel){
            $objModel = new SalesDataModel();
        }
        $objModel->attributes = $arrData;
        $objModel->save(false);
        return true;
    }

    /**
     * 获取本地对应报名信息
     * 相隔三天的数据????
     * @param type $product_id
     * @param type $orders_create_time
     * @return type
     */
    public function getGoodsIndo($ProductID, $orders_create_time) {
        if (empty($ProductID) || empty($orders_create_time)) {
            return false;
        }
        $model = GoodsModel::model();
        $where = array(
            'ProductID' => $ProductID,
            //'StartTime' => array(array('EGT', $orders_create_time - 86400 * 3), array('ELT', $orders_create_time + 86400 * 3), 'and'),
            'order' => 'GoodsID desc',
        );
        $criteria = $this->where($where);
        $data = $model->find($criteria);
        if (empty($data)) {
            return $data;
        }
        $goodsBm = GoodsBmModel::model()->findByPk($data->GoodsBmID);
        if (!empty($goodsBm)) {
            return array_merge($goodsBm->attributes, $data->attributes);
        }
        return $data->attributes;
    }

    /**
     * 删除指定日期数据
     * @return boolean
     */
    public function deleteAsTime() {
        $start_time = Yii::app()->request->getParam('start_time');
        if (empty($start_time)) {
            $this->addError('', '请输入要删除的日期');
            return FALSE;
        }
        $end_time = strtotime($start_time) + 86399;
        $where = array('TCreateTime' => array(array('EGT', strtotime($start_time)), array('ELT', $end_time), 'AND'));
        $criteria = $this->where($where);
        $data = $this->findAll($criteria);
        if (empty($data)) {
            $this->addError('', '没找到要删除的数据');
            return FALSE;
        }
        foreach ($data as $t) {
            $t->delete();
        }
        return true;
    }

    /**
     * 获取订单官网数
     * @param type $goods_id
     * @param type $start_time
     * @param type $end_time
     * @return type
     */
    public function getTurnoverGuan($goods_id, $start_time, $end_time) {
        $where = array(
            'Source' => 0,
            'GoodsID' => $goods_id,
            'TCreateTime' => array(array('GT', $start_time), array('LT', $end_time), 'AND'),
        );
        return SalesDataModel::model()->count($this->where($where));
    }

    /**
     * 获取订单优站数
     * @param type $goods_id
     * @param type $start_time
     * @param type $end_time
     * @return type
     */
    public function getTurnoverYou($goods_id, $start_time, $end_time) {
        $where = array(
            'Source' => 1,
            'GoodsID' => $goods_id,
            'TCreateTime' => array(array('GT', $start_time), array('LT', $end_time), 'AND'),
        );
        return SalesDataModel::model()->count($this->where($where));
    }
    /**
     * 获取订单总数
     * @param type $goods_id
     * @param type $start_time
     * @param type $end_time
     * @return type
     */
    public function getTurnover($goods_id, $start_time, $end_time) {
        $where = array(
            'GoodsID' => $goods_id,
            'TCreateTime' => array(array('GT', $start_time), array('LT', $end_time), 'AND'),
        );
        return SalesDataModel::model()->count($this->where($where));
    }

    public function beforeSave(){
        if($this->IsNewRecord){
            $this->AddTime = TIME_TIME;
        }
        return true;
    }   

}
